//
//  RadarListController.m
//  Stock
//
//  Created by sun black on 11-11-27.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "RadarListController.h"
#import "RadarSettingListController.h"
#import "ActiveController.h"
#import "QuestionViewController.h"
#import "SettingViewController.h"
#import "WhySyncViewController.h"

@implementation RadarListController

@synthesize radarTypeList;
@synthesize localRadars;
@synthesize titleViews;
@synthesize tableView=_tableView;
@synthesize radarSetting;
@synthesize appService;



-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    NSString *action = [aUserinfo objectForKey:kASIHttpRequestUserinfoKey];
    if ([action isEqualToString:kStockAppServiceModifySystemRadar]) {
        NSString *radarId = [aUserinfo objectForKey:@"radarId"];
        NSString *radarState = [aUserinfo objectForKey:@"radarState"];
        [self.radarSetting setObject:[NSNumber numberWithInt:[radarState intValue]] forKey:radarId];
        [self.radarSetting writeToFile:kRadarSettingFile atomically:YES];
    }else if([kPurchaseProduct isEqualToString:action]){
        if (manualPurchage) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"购买成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            [alert release];
            
            manualPurchage = NO;
        }
    }
    [self.view showHUDLoadingView:NO];
}

-(void)requestFinishedwithError:(NSError *)aError andUserinfo:(NSDictionary *)aUserinfo{
    [self.view showHUDLoadingView:NO];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
-(IBAction)wantBuy:(id)sender{
    if ([StockContext shareInstance].savedChargeEmail.length!=0) {
        [self gotoBuy];
        return;
    }
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"同步购买" destructiveButtonTitle:@"购买" otherButtonTitles:nil];
    [actionSheet showFromTabBar:self.tabBarController.tabBar];
    [actionSheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"clickedButtonAtIndex:%d",buttonIndex);
    if (buttonIndex==0) {
        [self gotoBuy];
    }else {
        WhySyncViewController *whySync = [[WhySyncViewController alloc] initWithNibName:@"WhySyncViewController" bundle:nil];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:whySync];
        [self presentModalViewController:nav animated:YES];
        [nav release];
        [whySync release];
        //[[StockAppHelper shareInstance] showAlertViewWithMessage:@"请到 关于->同步购买 选项中登录。"];
    }
}

-(void)gotoBuy{
    [[StoreKitContext shareInstance] purchaseProduct:@"H1_Card"];
    [self.view showHUDLoadingView:YES];
    manualPurchage = YES;
}

-(IBAction)answerQuestions:(id)sender{
    QuestionViewController *controller = [[QuestionViewController alloc] initWithStyle:UITableViewStylePlain];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}

-(void)switchRadar:(id)sender{
    UISwitch *temp = (UISwitch *)sender;
    [appService modifySystemRadar:[NSString stringWithFormat:@"%d",temp.tag] state:temp.on];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationItem.titleView = [StockAppHelper titleViewForNavigationItemWithString:@"股市雷达"];
   
    self.titleViews = [NSMutableArray array];
    for(int i=250;i<260;i++){
        UIView *view = [self.view viewWithTag:i];
        if (view) {
            [titleViews addObject:view];
        }
        [view removeFromSuperview];
    }
    
    
    self.appService = [[[StockAppService alloc] initWithDelegate:self] autorelease];
    
    self.radarSetting = [NSMutableDictionary dictionaryWithContentsOfFile:kRadarSettingFile]?:[NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"1",[NSNumber numberWithBool:YES],@"2",[NSNumber numberWithBool:YES],@"3",[NSNumber numberWithBool:YES],@"4",[NSNumber numberWithBool:YES],@"5",[NSNumber numberWithBool:YES],@"6", nil];
    
    self.radarTypeList = [NSArray arrayWithObjects:@"涨停",@"跌停",@"涨停打开",@"跌停打开",@"快速上涨",@"快速下跌",nil];
    self.localRadars = [NSMutableArray arrayWithArray:[StockRadar allVilidObject]];
    
    [self updateRadarDate];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateRadarDate) name:kNeedUpdateRadarDateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reciveDeleteStockNotification:) name:DeleteStockNotification object:nil];
    
    /*UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"关于" style:UIBarButtonItemStyleBordered target:self action:@selector(aboutUs)];
    self.navigationItem.rightBarButtonItem = rightButton;
    [rightButton release];
    */
    [StoreKitContext shareInstance].delegate = self;
    
}




-(void)aboutUs{
    
    SettingViewController *controller = [[SettingViewController alloc] initWithNibName:@"SettingViewController" bundle:nil];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
    navigationController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:navigationController animated:YES];
    [controller release];
    [navigationController release];
}

-(void)reciveDeleteStockNotification:(NSNotification *)notification{
    [self.navigationController popToRootViewControllerAnimated:NO];
    [self.localRadars removeAllObjects];
    [self.localRadars addObjectsFromArray:[StockRadar allVilidObject]];
    [self.tableView reloadData];
}

-(void)updateRadarDate{
    for (UIView *titleView in titleViews) {
        UILabel *label = (UILabel *)[titleView viewWithTag:999];
        if ([[StockContext shareInstance] getRadaDate].length>0) {
            label.text = [[StockContext shareInstance] getRadaDate];
        }
        
    }
    UIView *headerView = nil;//[titleViews objectAtIndex:]
    switch ([[StockContext shareInstance] radarStatus]){
        case RadarServiceStatuNormal:
            headerView = nil;
            break;
        default:
            headerView = [titleViews objectAtIndex:[[StockContext shareInstance] radarStatus]];
            break;
    }
    self.tableView.tableHeaderView = headerView;
}
-(void)dealloc{
    self.radarTypeList = nil;
    self.localRadars = nil;
    self.titleViews = nil;
    self.tableView = nil;
    self.radarSetting = nil;
    [self.appService cancleAllRequest];
    self.appService = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];

}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.radarSetting writeToFile:kRadarSettingFile atomically:YES];
    NSLog(@"viewWillDisappear");
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    self.radarTypeList = nil;
    self.titleViews = nil;
    self.tableView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 7;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"RadarListCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.font = [UIFont systemFontOfSize:17.0];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
        cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right_extend.png"]] autorelease];
        
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSString *imageName = @"cellbg2.png";
    if (indexPath.row%2==1) {
        imageName = @"cellbg1.png";
    }
    cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]] autorelease];
    
    UISwitch *switchView = (UISwitch *)[cell viewWithTag:987];
    switchView.hidden = indexPath.row==0?YES:NO;
    if (indexPath.row==0) {
        cell.textLabel.text = @"阀值预警";
        cell.detailTextLabel.text = [NSString stringWithFormat:@"已设置%d个预警阀值",localRadars.count];
        cell.detailTextLabel.textColor = [UIColor grayColor];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }else{
        UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 79.0, 27.0)];
        switchView.tag = indexPath.row;
        [switchView addTarget:self action:@selector(switchRadar:) forControlEvents:UIControlEventValueChanged];
        cell.accessoryView = switchView;
        [switchView release];
        NSNumber *number = [self.radarSetting objectForKey:[NSString stringWithFormat:@"%d",indexPath.row]];
        switchView.on = [number boolValue];
        cell.textLabel.text = [radarTypeList objectAtIndex:indexPath.row-1];
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        RadarSettingListController *controller = [[RadarSettingListController alloc] initWithNibName:@"RadarSettingListController" bundle:nil];
        controller.localRadars = self.localRadars;
        [self.navigationController pushViewController:controller animated:YES];
        [controller release];
    }
}

@end
